package com.egg.ylt.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.overlay.WalkRouteOverlay;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.egg.ylt.R;
import com.egg.ylt.Utils.AMapUtil;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.presenter.impl.ShopPositionMapViewPresenterImpl;
import com.egg.ylt.view.IShopPositionMapView;
import com.ruffian.library.widget.RImageView;
import com.ruffian.library.widget.RTextView;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.CommonUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created By Dlx
 * on 2018/12/11
 */
public class ACT_ShopPositionMapView extends BaseActivity<ShopPositionMapViewPresenterImpl> implements IShopPositionMapView, LocationSource, AMapLocationListener, RouteSearch.OnRouteSearchListener {
    @BindView(R.id.act_map_view)
    MapView actMapView;
    @BindView(R.id.shopposition_amap_btn)
    RTextView shoppositionAmapBtn;
    @BindView(R.id.shopposition_cancel_btn)
    RTextView shoppositionCancelBtn;

    AMap aMap;
    OnLocationChangedListener onLocationChangedListener;
    AMapLocationClient aMapLocationClient;
    AMapLocationClientOption option;
    @BindView(R.id.act_map_back)
    RImageView actMapBack;

    LatLng position;
    private RouteSearch mRouteSearch;
    LatLonPoint startPosition, endPosition;
    String shopAddress;
    CameraUpdate cameraUpdate;
    private String shopName;

    private double myLat;
    private double myLng;
    private LatLonPoint myPosition;

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_mapview;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void initViewsAndEvents() {
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        StatusBarUtil.setStatusBarColor(this, R.color.transparent);
        StatusBarUtil.StatusBarLightMode(this);
//        CustomUtils.setImmersiveStatusBar(mContext, mIncludeRlView);

        aMap = actMapView.getMap();
        actMapView.onCreate(savedInstanceState);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
//        double myLat = getIntent().getDoubleExtra("myLat", 0.0d);
//        double myLng = getIntent().getDoubleExtra("myLng", 0.0d);
        shopName = getIntent().getStringExtra("shopName");
        shopAddress = getIntent().getStringExtra("shopAddress");
        endPosition = new LatLonPoint(getIntent().getDoubleExtra("shopLat"
                , 0.0d), getIntent().getDoubleExtra("shopLng", 0.0d));
        if (myLat == 0.0d) {
            setUpMap();
        } else {

            startPosition = new LatLonPoint(myLat, myLng);
//            startPosition = new LatLonPoint(myLat,myLng);
//            setfromandtoMarker(startPosition, endPosition);

        }
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);

        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setScrollGesturesEnabled(false);
        uiSettings.setScaleControlsEnabled(false);
        uiSettings.setZoomGesturesEnabled(false);
        uiSettings.setZoomControlsEnabled(false);
        aMapLocationClient = new AMapLocationClient(getApplicationContext());
        aMapLocationClient.setLocationListener(this);
        option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        option.setOnceLocationLatest(true);
        aMapLocationClient.setLocationOption(option);
        aMapLocationClient.startLocation();

    }

    private void setUpMap() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.location_marker));
//        myLocationStyle.strokeColor(Color.BLACK);
//        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
//        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        Log.e("setUpMap: ", "invoke");

    }

    @Override
    protected void onResume() {
        super.onResume();
        actMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        actMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        actMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        actMapView.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @OnClick({R.id.shopposition_amap_btn, R.id.shopposition_cancel_btn, R.id.act_map_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.shopposition_amap_btn:
                if (mPresenter != null)
                    mPresenter.invokeAmap(endPosition.getLatitude(), endPosition.getLongitude());
                break;
            case R.id.shopposition_cancel_btn:
                if (cameraUpdate != null)
                    changeCamera(cameraUpdate);
                break;
            case R.id.act_map_back:
                finish();
                break;
        }
    }

    private void changeCamera(CameraUpdate cameraUpdate) {
        aMap.animateCamera(cameraUpdate);
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        this.onLocationChangedListener = onLocationChangedListener;
        if (aMapLocationClient == null) {
            aMapLocationClient = new AMapLocationClient(this);
            option = new AMapLocationClientOption();
            //设置定位监听
            aMapLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setOnceLocation(true);
            option.setOnceLocationLatest(true);
            //设置定位参数
            aMapLocationClient.setLocationOption(option);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            aMapLocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {

    }

    //amapLoactionChanged
//    @Override
//    public void onLocationChanged(AMapLocation aMapLocation) {
//        if (onLocationChangedListener != null && aMapLocation != null) {
//            if (aMapLocation != null
//                    && aMapLocation.getErrorCode() == 0) {
////                onLocationChangedListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
////                endPosition = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
//                myLat = aMapLocation.getLatitude();
//                myLng = aMapLocation.getLongitude();
//
//                search(aMapLocation.getLatitude(), aMapLocation.getLongitude());
//            } else {
//                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
//                Log.e("AmapErr", errText);
//            }
//        }
//    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                // 可在其中解析amapLocation获取相应内容。
//                CommonUtils.makeEventToast(this, amapLocation.getLongitude() + "," + amapLocation.getLatitude(), false);
//                LatLng position = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
//                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(position, 17, 0, 0));
//                changeCamera(cameraUpdate);
//                addMarker(position);
//                myPosition = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());

                startPosition = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());

                setfromandtoMarker(startPosition, endPosition);

            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }


    @Override
    public void invokeAmapApp(Intent intent) {
        readyGo(intent);
    }

    private void search(double lat, double lng) {
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(new LatLonPoint(lat, lng), endPosition);
        RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo);
        mRouteSearch.calculateWalkRouteAsyn(query);// 异步路径规划步行模式查询
    }


    private void setfromandtoMarker(LatLonPoint start, LatLonPoint end) {
        aMap.addMarker(new MarkerOptions()
                .position(AMapUtil.convertToLatLng(start))
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.location_marker)));
        MarkerOptions endMarker = new MarkerOptions();
        endMarker.position(AMapUtil.convertToLatLng(end));
        endMarker.icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_icon_position));
        endMarker.title(shopName);
        endMarker.snippet(shopAddress);
        Marker marker = aMap.addMarker(endMarker);
        marker.showInfoWindow();
        LatLngBounds bounds;
        LatLngBounds.Builder builder = LatLngBounds.builder();
        builder.include(AMapUtil.convertToLatLng(start));
        builder.include(AMapUtil.convertToLatLng(end));
        bounds = builder.build();

        cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 50);

        changeCamera(cameraUpdate);
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

    }

    private WalkRouteResult mWalkRouteResult;

    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {
        aMap.clear();// 清理地图上的所有覆盖物
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mWalkRouteResult = result;
                    final WalkPath walkPath = mWalkRouteResult.getPaths()
                            .get(0);
                    WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(
                            this, aMap, walkPath,
                            mWalkRouteResult.getStartPos(),
                            mWalkRouteResult.getTargetPos());
                    walkRouteOverlay.setNodeIconVisibility(false);
                    walkRouteOverlay.removeFromMap();
                    walkRouteOverlay.addToMap();
                    walkRouteOverlay.zoomToSpan();
                    setfromandtoMarker(mWalkRouteResult.getStartPos(), mWalkRouteResult.getTargetPos());
                    int dis = (int) walkPath.getDistance();
                    int dur = (int) walkPath.getDuration();
                    String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";


                } else if (result != null && result.getPaths() == null) {
                    CommonUtils.makeEventToast(this, "failed", false);
                }

            } else {
                CommonUtils.makeEventToast(this, "failed", false);
            }
        } else {
            CommonUtils.makeEventToast(this, errorCode, false);
        }
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

}
